/**
 * File: FPS.cs
 * Date: 20-03-2008
 * Auth: Jan-Jaap Severs
 * Desc: A component that renders the Frames Per Second of the application.
 */

#region Using statements

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

#endregion

namespace Gremlin.Components
{
    /// <summary>
    /// A component that renders the Frames Per Second of the application on-screen.
    /// </summary>
    public class FPS : DrawableGameComponent
    {
        #region Member variables

        private ContentManager _contentManager;
        private SpriteBatch _spriteBatch;
        private SpriteFont _font;

        private float _elapsedTime;
        private float _totalFrames;
        private float _fps;

        #endregion

        /// <summary>
        /// Creates a new FPS counter component.
        /// </summary>
        /// <param name="game">The host application.</param>
        public FPS(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            _contentManager = new ContentManager(game.Services, "Content");
        }

        /// <summary>
        /// Creates a SpriteBatch object and loads the font.
        /// </summary>
        protected override void LoadContent()
        {            
            _spriteBatch = new SpriteBatch(GraphicsDevice);
            _font = _contentManager.Load<SpriteFont>("Fonts/FPS");

            base.LoadContent();
        }

        /// <summary>
        /// Updates the FPS counter.
        /// </summary>
        /// <param name="gameTime">Timing information.</param>
        public override void Update(GameTime gameTime)
        {
            _elapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
            _totalFrames++;

            if (_elapsedTime >= 1.0f)
            {
                _fps = _totalFrames;
                _totalFrames = 0;
                _elapsedTime = 0;
            }
            
            base.Update(gameTime);
        }

        /// <summary>
        /// Draws the current FPS on screen.
        /// </summary>
        /// <param name="gameTime">Timing information.</param>
        public override void Draw(GameTime gameTime)
        {
            _spriteBatch.Begin();
            _spriteBatch.DrawString(_font, " FPS: " + _fps.ToString(), new Vector2(40.0f, 10.0f +
                _font.MeasureString(_fps.ToString()).Y), Color.White);
            _spriteBatch.End();
            GraphicsDevice.RenderState.DepthBufferEnable = true;
            base.Draw(gameTime);
        }
    }
}
